﻿using Microsoft.AspNetCore.Mvc;
using WZN_VoteSys.Models.Database;
using WZN_VoteSys.service;
using System.Linq;
using Microsoft.AspNetCore.Authorization;

namespace WZN_VoteSys.Controllers
{
    [Route("[controller]/[action]")]
    [ApiController]
    public class UsersController : ControllerBase
    {
        private readonly IJWTService _jwtService;
        private readonly WZN_VoteSysContext _db;
        public UsersController(IJWTService jwtService, WZN_VoteSysContext db)
        {
            _jwtService = jwtService;
            _db = db;
        }


        /// <summary>
        /// 用户注册（用户使用邮箱，密码进行注册，密码需要二次确认）
        /// </summary>
        /// <param name="Email"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        [HttpPost]
        public string Registered(string Email, string password1, string password2)
        {
            if (password1 != password2)
            {
                return "您输入的两次密码错误";
            }
            if (_db.Users.FirstOrDefault(x => x.Email == Email) != null)
            {
                return "您的邮箱已经注册";
            }
            User user = new User();
            user.Email = Email;
            user.Password = MD5Helper.MD5Encrypt32(password2);
            _db.Users.Add(user);
            if (_db.SaveChanges() > 0)
            {
                return "注册成功";
            }
            else
            {
                return "注册失败";
            }
        }


        /// <summary>
        /// 用户登录（用户使用邮箱，密码进行登录，登录后可访问需要授权的页面）
        /// </summary>
        /// <param name="Email"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        [HttpPost]
        public string Login(string Email, string password)
        {
            if (Email == null || password == null)
            {
                return "请输入登录账号或密码";
            }
            User user = _db.Users.FirstOrDefault(x => x.Email == Email);
            if (user == null)
            {
                return "该邮箱未注册，请先注册";
            }
            if (user.Password == MD5Helper.MD5Encrypt32(password))
            {
                return _jwtService.CreateToken(user.Email, user.Password);
            }
            else
            {
                return "密码错误";
            }
        }
    }
}
